<template>
	<view class="inbound-container">
		<!-- 搜索栏及两侧按钮 -->
		<view class="search-row">
			<u-button class="icon-btn" type="success" size="mini" @click="onScanInbound"
				:custom-style="{ padding: '0 16rpx', marginRight: '10rpx' }">
				<u-icon name="scan" size="24" color="#333"></u-icon>
			</u-button>
			<view class="search-box-flex">
				<u-search v-model="searchKeyword" placeholder="搜索订单号、商品名称、供应商" :show-action="false" :clearabled="true"
					@search="onSearch" @custom="onSearch" @clear="onClear"></u-search>
			</view>
			<u-button class="icon-btn" type="success" size="mini" @click="onScanInbound"
				:custom-style="{ padding: '0 16rpx', marginRight: '10rpx' }">
				<u-icon name="scan" size="24" color="#333"  ></u-icon>
			</u-button>
		</view>

		<!-- tabs页签 -->
		<view class="tabs-section">
			<u-tabs :list="tabList" v-model:current="currentTab" @change="onTabChange" lineColor="#2979ff"
				:activeStyle="{ color: '#2979ff', fontWeight: 'bold' }" :inactiveStyle="{ color: '#666' }"></u-tabs>
		</view>

		<!-- 列表区域 -->
		<view class="list-section">
			<!-- 订单列表 -->
			<view class="order-list">
				<view class="order-item" v-for="(item, index) in orderList" :key="item.id" @click="onOrderClick(item)">
					<view class="order-header">
						<view class="order-info">
							<text class="order-number">{{ item.container_track_no }}</text>
							<u-tag :text="item.status_code_name" :type="getStatusType(item.status_code)" size="mini"></u-tag>
						</view>
						<view class="order-date">
							<text class="date-text">{{ formatDate(item.createdate) }}</text>
						</view>
					</view>

					<view class="order-content">
						<view class="supplier-info">
							<u-icon name="account" size="16" color="#666"></u-icon>
							<text class="supplier-text">{{ item.supplierName }}</text>
						</view>
						<view class="goods-info">
							<text class="goods-text">{{ item.skuNum }}种商品</text>
							<text class="quantity-text">共{{ item.cartons_count }}{{item.arrival_type_name}}</text>
						</view>
						<view class="box-info">
							<view class="box-meta">
								<text class="box-text">体积: {{ item.volume || '--' }} CBM</text>
								<text class="box-text">重量: {{ item.weight || '--' }} KG</text>
							</view>
						</view>
					</view>

					<view class="order-footer">
						<view class="progress-info">
							<text class="progress-text">入库进度: {{ item.received_num }}/{{ item.cartons_count }}</text>
							<u-line-progress :percentage="getProgressPercentage(item)" :show-text="false"
								height="6"></u-line-progress>
						</view>
						<view class="action-buttons">
							<u-button v-if="item.status === 'pending'" type="primary" size="mini" @click.stop="onStartInbound(item)">
								开始入库
							</u-button>
							<u-button v-if="item.status === 'processing'" type="success" size="mini"
								@click.stop="onContinueInbound(item)">
								继续入库
							</u-button>
							<u-button v-if="item.status === 'completed'" type="info" size="mini" @click.stop="onViewDetail(item)">
								查看详情
							</u-button>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore">
				<u-loadmore :status="loadMoreStatus" @loadmore="onLoadMore"></u-loadmore>
			</view>
			<!-- 到底了提示 -->
			<view class="no-more" v-if="!hasMore && orderList.length > 0">
				<text class="no-more-text">—— 到底了 ——</text>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="orderList.length === 0 && !loading">
				<u-empty text="暂无入库订单" mode="list"></u-empty>
			</view>
		</view>

		<!-- 筛选弹窗 -->
		<u-popup v-model="showFilterModal" mode="bottom" :closeable="true" :round="10">
			<view class="filter-modal">
				<view class="filter-header">
					<text class="filter-title">筛选条件</text>
				</view>
				<view class="filter-content">
					<view class="filter-item">
						<text class="filter-label">订单状态</text>
						<u-radio-group v-model="filterStatus" @change="onFilterChange">
							<u-radio v-for="status in statusOptions" :key="status.value" :name="status.value"
								:label="status.label"></u-radio>
						</u-radio-group>
					</view>
					<view class="filter-item">
						<text class="filter-label">时间范围</text>
						<u-datetime-picker v-model="filterDateRange" mode="range" @confirm="onDateRangeChange"></u-datetime-picker>
					</view>
				</view>
				<view class="filter-actions">
					<u-button @click="onResetFilter">重置</u-button>
					<u-button type="primary" @click="onApplyFilter">确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import api from "@/api"
const INBOUND_CODE = {
	PEDDING: 110,
	IN: 120
}

export default {
	data() {
		return {
			// 搜索相关
			searchKeyword: '',

			// 筛选相关
			showFilterModal: false,
			filterStatus: INBOUND_CODE.PEDDING,
			filterDateRange: [],

			// 列表数据
			orderList: [],
			loading: false,
			hasMore: true,
			loadMoreStatus: 'loadmore',

			// 分页参数
			page: 1,
			pageSize: 10,

			// 统计数据
			totalCount: 0,
			pendingCount: 0,
			completedCount: 0,

			// 状态选项
			statusOptions: [
				{ label: '全部', value: '' },
				{ label: '待入库', value: INBOUND_CODE.PEDDING },
				{ label: '入库中', value: 'processing' },
				{ label: '已完成', value: 'completed' },
				{ label: '已取消', value: 'cancelled' }
			],

			// tabs相关
			tabList: [
				{ name: '全部', value: '' },
				{ name: '待入库(0)', value: INBOUND_CODE.PEDDING },
				{ name: '已完成(0)', value: 'completed' }
			],
			currentTab: 0,
		}
	},
	onLoad() {
		this.loadOrderList()
		this.loadStatistics()
	},
	onPullDownRefresh() {
		this.refreshData()
	},
	onReachBottom() {
		if (this.hasMore && this.loadMoreStatus === 'loadmore') {
			this.onLoadMore()
		}
	},
	methods: {
		// 加载订单列表
		async loadOrderList(isLoadMore = false) {
			if (this.loading) return

			this.loading = true
			if (!isLoadMore) {
				this.page = 1
				this.orderList = []
			}

			try {
				// 模拟API调用
				const params = {
					page: {
						current: this.page,
						size: this.pageSize,
					},
					data: {
						task_status: this.filterStatus,
						status_code: this.filterStatus
					}
				}

				// 模拟数据
				const res = await api.inbound.getInboundList('selectOrderList', params)
				const arr = res.data.data.data;
				this.orderList = this.orderList.concat(arr);

				this.hasMore = Boolean(arr?.length);
				this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore'

				if (isLoadMore) {
					this.page++
				}

			} catch (error) {
				console.error('加载订单列表失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				uni.stopPullDownRefresh()
			}
		},

		// 加载统计数据
		async loadStatistics() {
			try {
				// 模拟统计数据
				this.totalCount = 156
				this.pendingCount = 23
				this.completedCount = 133
				// 更新tab数量
				this.tabList = [
					{ name: `待入库(${this.pendingCount})`, value: INBOUND_CODE.PEDDING },
					{ name: `已完成(${this.completedCount})`, value: 'completed' }
				]
			} catch (error) {
				console.error('加载统计数据失败:', error)
			}
		},

		// 生成模拟数据
		getMockData(params) {
			const mockList = []
			const startIndex = (params.page - 1) * params.pageSize

			for (let i = 0; i < params.pageSize; i++) {
				const index = startIndex + i
				if (index >= 156) break // 模拟总数据量

				const statuses = [INBOUND_CODE.PEDDING, 'processing', 'completed', 'cancelled']
				const status = statuses[Math.floor(Math.random() * statuses.length)]

				const order = {
					id: `IN${String(index + 1).padStart(6, '0')}`,
					orderNo: `IN${String(index + 1).padStart(6, '0')}`,
					status: status,
					supplierName: `供应商${index + 1}`,
					goodsCount: Math.floor(Math.random() * 10) + 1,
					totalQuantity: Math.floor(Math.random() * 100) + 10,
					inboundQuantity: status === 'completed' ? Math.floor(Math.random() * 100) + 10 :
						status === 'processing' ? Math.floor(Math.random() * 50) + 5 : 0,
					createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
					length: Math.floor(Math.random() * 60) + 20, // cm
					width: Math.floor(Math.random() * 40) + 20, // cm
					height: Math.floor(Math.random() * 40) + 20, // cm
					volume: (Math.random() * 1.5 + 0.1).toFixed(2), // m³
					weight: (Math.random() * 30 + 1).toFixed(1), // kg
				}

				// 根据筛选条件过滤
				if (params.keyword && !order.orderNo.includes(params.keyword) &&
					!order.supplierName.includes(params.keyword)) {
					continue
				}

				if (params.status && order.status !== params.status) {
					continue
				}

				mockList.push(order)
			}

			return {
				list: mockList,
				hasMore: startIndex + params.pageSize < 156
			}
		},

		// 搜索
		onSearch() {
			this.loadOrderList()
		},

		// 清除搜索
		onClear() {
			this.searchKeyword = ''
			this.loadOrderList()
		},

		// 刷新数据
		onRefresh() {
			this.refreshData()
		},

		// 刷新数据
		refreshData() {
			this.loadOrderList()
			this.loadStatistics()
		},

		// 加载更多
		onLoadMore() {
			if (this.hasMore && !this.loading) {
				this.loadMoreStatus = 'loading'
				this.loadOrderList(true)
			}
		},

		// 筛选变化
		onFilterChange() {
			// 筛选条件变化时的处理
		},

		// 日期范围变化
		onDateRangeChange(e) {
			this.filterDateRange = e
		},

		// 重置筛选
		onResetFilter() {
			this.filterStatus = ''
			this.filterDateRange = []
		},

		// 应用筛选
		onApplyFilter() {
			this.showFilterModal = false
			this.loadOrderList()
		},

		// 新增入库
		onAddInbound() {
			uni.navigateTo({
				url: '/pages/inbound/add/add'
			})
		},

		// 扫一扫入库
		onScanInbound() {
			uni.scanCode({
				success: (res) => {
					console.log('扫码结果:', res.result)
					// 处理扫码结果，可以跳转到相应的页面
					uni.showToast({
						title: '扫码成功',
						icon: 'success'
					})
					// 这里可以根据扫码结果跳转到相应的页面
					// uni.navigateTo({
					// 	url: `/pages/inbound/scan-result/scan-result?code=${res.result}`
					// })
				},
				fail: (err) => {
					console.log('扫码失败:', err)
					uni.showToast({
						title: '扫码失败',
						icon: 'none'
					})
				}
			})
		},

		// 订单点击
		onOrderClick(item) {
			uni.navigateTo({
				url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
			})
		},

		// 开始入库
		onStartInbound(item) {
			uni.navigateTo({
				url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
			})
		},

		// 继续入库
		onContinueInbound(item) {
			uni.navigateTo({
				url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
			})
		},

		// 查看详情
		onViewDetail(item) {
			uni.navigateTo({
				url: `/pages/inbound/detail?id=${item.guid}&supplierName=${item.supplierName}&inboundTime=${item.createTime}`
			})
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				[INBOUND_CODE.PEDDING]: '待入库',
				'processing': '入库中',
				'completed': '已完成',
				'cancelled': '已取消'
			}
			return statusMap[status] || '未知'
		},

		// 获取状态类型
		getStatusType(status) {
			const typeMap = {
				[INBOUND_CODE.PEDDING+'']: 'warning',
				'processing': 'primary',
				'completed': 'success',
				'cancelled': 'error'
			}
			return typeMap[status] || 'info'
		},

		// 获取进度百分比
		getProgressPercentage(item) {
			if (item.cartons_count === 0) return 0
			return Math.round((item.received_num / item.cartons_count) * 100)
		},

		// 格式化日期
		formatDate(dateString) {
			const date = new Date(dateString)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
		},

		onTabChange(index) {
			this.currentTab = index;
			this.filterStatus = this.tabList[index].value;
			this.loadOrderList();
		},
	}
}
</script>

<style lang="scss" scoped>
.inbound-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 20rpx;
}

// 搜索区域
.search-row {
	display: flex;
	align-items: center;
	background: #fff;
	padding: 20rpx 20rpx 0 20rpx;

	.search-box-flex {
		flex: 1;
	}

	.icon-btn {
		border-radius: 50%;
		padding: 0 !important;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: transparent !important;
		border: none !important;
		box-shadow: none !important;
	}
}

// tabs页签
.tabs-section {
	background: #fff;
	padding: 0 20rpx;
	margin-bottom: 20rpx;
}

// 列表区域
.list-section {
	background-color: #ffffff;
	margin: 0 20rpx;
	border-radius: 20rpx;
	padding: 40rpx 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

	.order-list {
		.order-item {
			background-color: #f8f9fa;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;
			border: 1rpx solid #e9ecef;

			.order-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 25rpx;

				.order-info {
					display: flex;
					align-items: center;

					.order-number {
						font-size: 32rpx;
						font-weight: bold;
						color: #333333;
						margin-right: 25rpx;
					}
				}

				.order-date {
					.date-text {
						font-size: 26rpx;
						color: #999999;
					}
				}
			}

			.order-content {
				margin-bottom: 25rpx;

				.supplier-info {
					display: flex;
					align-items: center;
					margin-bottom: 15rpx;

					.supplier-text {
						font-size: 30rpx;
						color: #666666;
						margin-left: 15rpx;
					}
				}

				.goods-info {
					display: flex;
					justify-content: space-between;

					.goods-text,
					.quantity-text {
						font-size: 26rpx;
						color: #666666;
					}
				}

				.box-info {
					display: flex;
					align-items: flex-start;
					margin-top: 12rpx;
					margin-bottom: 4rpx;

					.box-icon {
						margin-top: 2rpx;
					}

					.box-meta {
						display: flex;
						flex-wrap: wrap;
						gap: 24rpx;
					}

					.box-text {
						font-size: 24rpx;
						color: #888;
						line-height: 36rpx;
					}
				}
			}

			.order-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.progress-info {
					flex: 1;
					margin-right: 30rpx;

					.progress-text {
						font-size: 26rpx;
						color: #666666;
						margin-bottom: 15rpx;
						display: block;
					}
				}

				.action-buttons {
					display: flex;
					gap: 15rpx;

					::v-deep .u-button {
						min-width: 120rpx;
						height: 60rpx;
						font-size: 26rpx;
					}
				}
			}
		}
	}
}

// 加载更多
.load-more {
	margin-top: 40rpx;
}

// 空状态
.empty-state {
	margin-top: 120rpx;
}

// 筛选弹窗
.filter-modal {
	padding: 50rpx 40rpx;

	.filter-header {
		margin-bottom: 50rpx;

		.filter-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
		}
	}

	.filter-content {
		.filter-item {
			margin-bottom: 50rpx;

			.filter-label {
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 25rpx;
				display: block;
			}
		}
	}

	.filter-actions {
		display: flex;
		gap: 25rpx;
		margin-top: 50rpx;

		::v-deep .u-button {
			flex: 1;
			height: 80rpx;
			font-size: 30rpx;
		}
	}
}

// 适配App端的特殊样式
/* #ifdef APP-PLUS */
.search-row {
	padding: 40rpx 20rpx;
}

.stats-section {
	padding: 50rpx 30rpx;
}

.list-section {
	padding: 50rpx 30rpx;
}

.order-list .order-item {
	padding: 35rpx;
}

.filter-modal {
	padding: 60rpx 40rpx;
}

/* #endif */

// 适配不同屏幕尺寸
@media screen and (max-width: 750rpx) {
	.stats-section {
		padding: 30rpx 20rpx;

		.stats-item .stats-number {
			font-size: 40rpx;
		}
	}

	.list-section {
		padding: 30rpx 20rpx;
	}

	.order-list .order-item {
		padding: 25rpx;
	}
}

.no-more {
	text-align: center;
	color: #999;
	font-size: 28rpx;
	margin: 32rpx 0 0 0;
}
.no-more-text {
	padding: 0 24rpx;
	background: #f5f5f5;
	border-radius: 16rpx;
}
</style>